import { createSlice, createAsyncThunk } from '@reduxjs/toolkit'

const cartSlice = createSlice({
    name: 'cart',
    initialState: {
        cartList: []
    },
    // 定义的都是同步的方法
    reducers: {
        addCart(state, { payload }) {
            // 判断当前商品在 cartList中是否存在，如果存购买数量 + 1
            let index = state.cartList.findIndex(item => {
                return item.id === payload.id
            })
            if (index === -1) {
                // 不存在新增
                console.log('cart payload: ', payload)
                state.cartList.push({
                    ...payload,
                    buyNum: 1 // 购买数量1
                })
            } else {// 存在
                state.cartList[index].buyNum += 1
            }

        },
        //
        addNum(state, { payload }) {
            console.log('payload: ', payload)
            state.cartList = state.cartList.map(item => {
                if (item.id === payload) {
                    item.buyNum += 1;
                }
                return item;
            })
        },
        decNum(state, { payload }) {
            // 当前要修改buyNum元素的索引值
            let index = state.cartList.findIndex(item => item.id === payload);
            let count = state.cartList[index].buyNum - 1
            if (count <= 0) {// 删掉
                state.cartList.splice(index, 1)
            } else {// 数量 - 1
                state.cartList[index].buyNum = count;
            }

        }
    },
    // 异步的程序员
    extraReducers: (builder) => {
        builder
            .addCase(asyncAddNum.fulfilled, (state, { payload }) => {
                state.cartList = state.cartList.map(item => {
                    if (item.id === payload) {
                        item.buyNum += 1;
                    }
                    return item;
                })
            })
            .addCase(asyncAddNum.pending, (state, action) => {
                console.log('pending action: ', action)
            })
            .addCase(asyncAddNum.rejected, (state, action) => {
                console.log('rejected action: ', action);
            })
    }
})

export const { addCart, addNum, decNum } = cartSlice.actions;
export default cartSlice.reducer;

// 创建并暴露异步的actionCreator
// createAsyncThunk 调用的结果会返回一个新的函数，该函数执行的结果，返回一个promise对象
export const asyncAddNum = createAsyncThunk('cart/addNum', (payload) => {
    // 可以执行异步的方法，如果返回一个成功的Promise，那么会执行到extraReducers中 addCase fulfilled，如果是rejected，会执行到extraReducers中的 rejected函数
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            // reject(payload)
            resolve(payload);
        }, 2000)

    })
})



